<?php
/**
 * MongoDB数据库组件
 * @property string  $connectString  MongoDB数据库服务器及端口信息
 * @property string  $dbname         MongoDB数据库名
 * @property integer $try            尝试重新链接服务器次数
 */
class CMongoDB extends CComponent {
    /**
     * @var string MongoDB链接字符串
     */
    public $connectString = "mongodb://127.0.0.1:27017";
	
	/**
     * @var string MongoDB登陆帐号
     */
	public $username;
	
	/**
     * @var string MongoDB登陆密码
     */
	public $password;
	
	/**
     * @var boolean MongoDB是否进行登陆验证
     */
	public $auth = False;

    /**
     * @var string MongoDB数据库名称
     */
    public $dbname="images";

    /**
     * @var int 链接MongoDB失败的尝试次数
     */
    public $tryConnect=10;
    
    /**
     * @var MongoClient MongoDB实例
     */
    private $_instance;
    
    public function init() {
        $this->initrializeMongoDB();
    }
    
    /**
     * 初始化MongoDB链接
     */
    public function initrializeMongoDB() {
        $this->_instance = $this->Connect( $this->tryConnect );
        $this->_instance = $this->_instance->selectDB( $this->dbname );
    }
    
    /**
     * 代理执行MongoDB方法
     */
    public function __call( $method, $params ) {
        return call_user_func_array( array($this->_instance,$method), $params );
    }
    
    /**
     * 建立与MongoDB服务器的链接
     * @param integer $try 失败尝试建立链接的次数
     * @return MongoClient
     */
    protected function Connect( $again ) {
        if( $again === 0 ) {
            throw new CHttpException( 500, Yii::t('skypiea','Faild to connection MongoDB:{host}',
                array('{host}'=>$this->connectString)));
        }
        try{
			$options = array("db"=>$this->dbname, "connect"=>true);
			if($this->auth) {
				$options["username"] = $this->username;
				$options["password"] = $this->password;
			}
            $conn = @new MongoClient($this->connectString, $options);
            if(is_null($conn)) {
                throw new Exception("Try");
            }
            
            return $conn;
        }
        catch ( CException $err ) {
            Yii::log(Yii::t('skypiea','Try to connection MongoDB {index}',array('{index}'=>abs($again-4))),
                CLogger::LEVEL_WARNING, 'systemInfo');
            $again = $again-1;
            return $this->Connect( $again );
        }
    }
}